package list;

public class LinkedList<E>{
    private Node head;
    class Node{
        E data;
        Node next;
        Node prev;
        Node(E e){
            data = e;
        }
    }
    public boolean add(E e){
        Node node = new Node(e);
        if(head==null){
            head = node;
            head.next = head;
            head.prev = head;
            return true;
        }
        Node last = head.prev;
        head.prev = node;
        node.next = head;
        last.next = node;
        node.prev = last;
        return true;
    }
    public String toString(){
        //[xxx,xxx,xxx,xxx]
        if(head == null){
            return "[]";
        }
        StringBuilder sb = new StringBuilder();
        //将头节点存放的元素添加到sb
        sb.append(head.data);
        //找到头节点的下一个节点
        Node node = head.next;
        //如果某个节点的下一个节点等于头节点,则不再向下遍历了
        while (node!=head){
            sb.append(","+node.data);
            node = node.next;
        }
        return "["+sb.toString()+"]";
    }
}